import { useStore } from '@/hooks';
import { Button, Dialog, Form } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { FieldsGrid } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';
import TauSimpleSelect from '@/components/TauSimpleSelect';

const FromItem = Form.Item;

const formItemLayout = {
  labelCol: {
    fixedSpan: 8,
  },
  wrapperCol: {
    span: 16,
  },
  style: { marginBottom: 20 },
};

const DataForm = ({ id, onCancel, modal, onSubmit, ...formProps }) => {
  const { integralStore: store, ruleStore } = useStore();
  const { show, record, toClose } = modal;
  const [driver] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [isViewMode] = useState(show === 'view');
  const [groupDataSource, setGroupDataSource] = useState([]);
  const [selectDataSource, setSelectDataSource] = useState([]);

  useEffect(() => {
    if (toClose?.startsWith?.('toClose')) handleCancel();
  }, [modal]);

  useEffect(() => {
    (async () => {
      const data = await store.getGroup({ search: {}, pg: { page: 0, size: 999, sort: ['crDate;desc'] } });
      setGroupDataSource(data);
      const source = await store.getMember({ groupIds: [ruleStore._group_id] });
      setSelectDataSource(source);
      if (id) {
        const res = await store.get(id);
        editCtx.origin = _.cloneDeep(res);
        _.assign(driver, res);
      } else {
        const findGroup = data.find((p) => p.value == ruleStore._group_id);
        _.set(driver, 'enable', false);
        _.set(driver, 'groupId', ruleStore._group_id);
        _.set(driver, 'groupName', findGroup?.label);
        _.set(driver, 'status', 3);
      }
    })();
  }, []);

  const overrideModel = {
    groupId: {
      ui: {
        renderer: (v) => <TauSimpleSelect value={v} disabled={ruleStore._group_id} dataSource={groupDataSource} placeholder={t`请选择群组`} />,
      },
    },
    buyerName: {
      ui: {
        renderer: (v) => <TauSimpleSelect value={v} showSearch dataSource={selectDataSource} placeholder={t`请选择买方`} />,
        itemProps: { required: true },
      },
    },
    sellerName: {
      ui: {
        renderer: (v) => <TauSimpleSelect value={v} showSearch dataSource={selectDataSource} placeholder={t`请选择卖方`} />,
        itemProps: { required: true },
      },
    },
  };

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = async (values, item) => {
    const { name, value } = item;
    _.set(driver, name, value);
    if (name === 'groupId') {
      const res = await store.getMember({ groupId: value });
      setSelectDataSource(res);
      const findObj = item?.field?.fieldsMeta?.groupId?.inputValues[2];
      _.assign(driver, {
        buyerName: '',
        buyerId: '',
        sellerName: '',
        sellerId: '',
        groupName: findObj?.label,
      });
    }
    if (name === 'buyerName') {
      const res = item?.field?.fieldsMeta?.buyerName?.inputValues[2];
      const { nickname, value: buyerId } = res;
      _.assign(driver, {
        buyerName: nickname,
        buyerId,
      });
    }
    if (name === 'sellerName') {
      const res = item?.field?.fieldsMeta?.sellerName?.inputValues[2];
      const { nickname, value: sellerId } = res;
      _.assign(driver, {
        sellerName: nickname,
        sellerId,
      });
    }
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: ActivityForm.jsx:213 _ errors:', errors);
      return;
    }
    onSubmit?.(driver);
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form style={{ marginTop: 20 }} {...formProps} value={driver} onChange={handleChange} colon useLabelForErrorMessage>
      <FieldsGrid
        formData={driver}
        mode={show == 'add' ? 'add' : 'view'}
        columns={1}
        itemLayout={{ ...formItemLayout, labelAlign: 'left' }}
        overrideModel={overrideModel}
        fields={['groupId', 'transactionType', 'buyerName', 'sellerName', 'points', 'price']}
      />
      <FieldsGrid
        formData={driver}
        mode={show}
        columns={1}
        itemLayout={{ ...formItemLayout, labelAlign: 'left' }}
        overrideModel={overrideModel}
        fields={['remarks']}
      />
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
};

export default observer(DataForm);
